/**
 * 
 */
package com.ntnhu2008.actionbar;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * @author Nguyen Nhu
 * 
 */
public class ActionBar extends RelativeLayout implements View.OnClickListener{

	Context mContext;
	ProgressBar progress;
	TextView title;
	LinearLayout actions;
	LayoutInflater layoutInflater;

	public ActionBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
			try{
			layoutInflater = LayoutInflater.from(context);
			View view = layoutInflater.inflate(R.layout.actionbar, this);
			progress = (ProgressBar) view.findViewById(R.id.process);
			actions = (LinearLayout) view.findViewById(R.id.actions);
			title = (TextView) view.findViewById(R.id.title);
			}catch(Exception e){
				e.printStackTrace();
			}
	

	}

	public void setTitle(CharSequence title){
		this.title.setText(title);
	}
	
	public void setFont(View v){
		Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "fonts/arial.ttf");
		((TextView) v).setTypeface(typeface);
	}
	
	public void addAction(Action action) {
        final int index = actions.getChildCount();
        addAction(action, index);
    }
	
	public void addAction(Action action, int index){
		actions.addView(inflateAction(action), index);
	}
	
	public void removeActionAt(int index){
		actions.removeViewAt(index);
	}
	
	public void removeAction(Action action){
		int childCount = getActionCount();
		for (int i = 0; i < childCount; i++) {
			View view = actions.getChildAt(i);
			if(view != null){
				Object tag = view.getTag();
				if(tag instanceof Action && tag.equals(action)){
					actions.removeView(view);
				}
			}
		}
	}
	
	public int getActionCount(){
		return actions.getChildCount();
	}
	
	private View inflateAction(Action action) {
		View view = layoutInflater.inflate(R.layout.actionbar_item, actions, false);
		ImageButton labelView = (ImageButton) view.findViewById(R.id.actionbar_item);
		labelView.setImageResource(action.getDrawable());
		view.setTag(action);
		view.setOnClickListener(this);
		return view;
	}

	@Override
	public void onClick(View v) {
		
		Object tag = v.getTag();
		if(tag instanceof Action){
			Action action = (Action) tag;
			action.performAction(v);
		}
	}

}
